package Demo5;

/**
 * Cloneable 的深拷贝和浅拷贝
 * 深浅拷贝跟 Cloneable 方法没有关系 都是克隆方法 跟代码的实现有关系
 */

class Money implements Cloneable{
    public double m = 19.9;

    @Override
    public String toString() {
        return "Money{" +
                "money=" + m +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Person implements Cloneable{
   //                     Cloneable是空接口
                        // 表明当前类 是可以被克隆的
    public String name;
    public int age;

    Money money = new Money();

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", money=" + money +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
                                    //可能会抛出异常/这个异常叫做 支持克隆异常 （属于编译时期的异常 ，先解决异常才能编译 ）

        Person tmp = (Person) super.clone();
        this.money = (Money) tmp.money.clone();
        return tmp;
    }
}
public class Text {
    //深拷贝

    public static void main(String[] args) throws CloneNotSupportedException{
        Person person1 = new Person("zhangsan" ,18);
        Person person2 = (Person) person1.clone();
        System.out.println(person2);
        System.out.println(person1);
        System.out.println("===================");
        person1.money.m= 199.9;//我们就得解决这个问题 当对 person1 的 m 进行该值时 person2 并未跟随改变
        System.out.println(person2);
        System.out.println(person1);
    }
    public static void main2(String[] args) throws CloneNotSupportedException{
        Person person1 = new Person("zhangsan" ,18);
        Person person2 = (Person) person1.clone();//看似拷贝成功了 但实际深处的引用对象没有拷贝
        System.out.println(person2);
        System.out.println(person1);
        System.out.println("===================");
        person1.money.m= 199.9;//看似成功了 但通过其中一个引用做改变 两个引用的对象都一起改变了
        System.out.println(person2);
        System.out.println(person1);
    }
    //浅拷贝
    public static void main1(String[] args) throws CloneNotSupportedException{
        Person person1 = new Person("zhangsan" ,18);
        Person person2 = (Person) person1.clone();
        System.out.println(person2);
        System.out.println(person1);
    }
}
